from datetime import date, datetime
import math
from wechatpy import WeChatClient
from wechatpy.client.api import WeChatMessage, WeChatTemplate
from borax.calendars.lunardate import LunarDate
import requests
import random
import time
import hashlib
import json

today_solar = datetime.now()
today_lunar = LunarDate.today()
today_solar_str = today_solar.strftime('%Y-%m-%d')
week_list = ["星期一","星期二","星期三","星期四","星期五","星期六","星期日"]
today_lunar_str = today_lunar.cn_md + " " + week_list[today_solar.weekday()]
# today1 = today_lunar.cn_year + "年 " + today_lunar.cn_month + "月" + today_lunar.cn_day + " 星期" + today_lunar.cn_week
# today_lunar_str = datetime.now().strftime('%Y-%m-%d') + ' ' + week_list[today_solar.weekday()]

city = "XX"
city1 = "XX"
birthday_lunar = "xxxx-xx-xx".split(",")
birthday_solar = "xx-xx-xx".split(",")
start_date = "2022-05-20"
exam_date = "2022-05-21"
province = "XX"
province1 = "XX"

data = {}

app_id = "xxxxxxx"
app_secret = "xxxxxxx"
user_ids = "xxxxxxx,yyyyyyy".split(",")
template_id = "xxxxxxx"
url = "https://waluna.top"


# 获取天气数据
def get_weather(city):
    url = "http://autodev.openspeech.cn/csp/api/v2.1/weather?openId=aiuicus&clientType=android&sign=android&city=" + city
    res = requests.get(url).json()
    weather = res['data']['list'][0]
    return weather['city'], weather['weather'], math.floor(weather['temp']), math.floor(weather['high']), math.floor(weather['low'])


# 获取疫情数据
def get_virus_old(province, city):
    url = "https://api.inews.qq.com/newsqa/v1/query/inner/publish/modules/list?modules=diseaseh5Shelf"
    req = requests.get(url)
    req_json = req.json()['data']['diseaseh5Shelf']['areaTree'][0]['children']

    for i in range(0, len(req_json)):
        if req_json[i]['name'] == province:
            # print(req_json[i])
            for j in range(0, len(req_json[i]['children'])):
                if req_json[i]['children'][j]['name'] == city:
                    req_data = req_json[i]['children'][j]['today']
                    return req_data['local_confirm_add'], req_data['wzz_add']
                    # print(req_json[i]['children'][j]['name'])
        # print(req_json)


# 获取疫情数据
def get_virus1(province, city):
    url = "https://voice.baidu.com/newpneumonia/getv2?from=mola-virus&stage=publish&target=trendCity&area=" + province + "-" + city
    req_json = requests.get(url).json()

    req_data = req_json['data'][0]['trend']['list']
    local_wzz_add = req_data[1]['data'][-1]
    local_confirm_add = req_data[2]['data'][-1]

    return local_wzz_add, local_confirm_add


def get_virus(province, city):
    url = "https://opendata.baidu.com/data/inner?resource_id=5653&query=" + province + city + \
          "%E6%96%B0%E5%9E%8B%E8%82%BA%E7%82%8E%E6%9C%80%E6%96%B0%E5%8A%A8%E6%80%81&alr=1"

    req_json = requests.get(url).json()
    req_data = req_json['Result'][0]['DisplayData']['resultData']['tplData']['data_list']

    local_wzz_add = req_data[0]['total_num']
    local_confirm_add = req_data[1]['total_num']

    dangerousAreas_str = req_json['Result'][0]['DisplayData']['resultData']['tplData']['dangerousAreas']
    dangerousAreas = json.loads(dangerousAreas_str)

    if 'highLevel' in dangerousAreas:
        dangerousAreas_high = dangerousAreas['highLevel']
    else:
        dangerousAreas_high = 0
    if 'midLevel' in dangerousAreas:
        dangerousAreas_mid = dangerousAreas['midLevel']
    else:
        dangerousAreas_mid = 0
    if 'lowLevel' in dangerousAreas:
        dangerousAreas_low = dangerousAreas['lowLevel']
    else:
        dangerousAreas_low = 0

    return local_wzz_add, local_confirm_add, dangerousAreas_high, dangerousAreas_mid, dangerousAreas_low


def get_dangerousAreas(province, city):
    """
    https://github.com/panghaibin/RiskLevelAPI
    http://bmfw.www.gov.cn/yqfxdjcx/risk.html
    """
    # Params from Ajax.js
    key = '3C502C97ABDA40D0A60FBEE50FAAD1DA'
    timestamp = str(int(time.time()))
    token = '23y0ufFl5YxIyGrI8hWRUZmKkvtSjLQA'
    nonce = '123456789abcdefg'
    pass_header = 'zdww'
    _ = timestamp + token + nonce + timestamp
    _ = _.encode('utf-8')
    signatureHeader = hashlib.sha256(_).hexdigest().upper()
    _ = timestamp + 'fTN2pfuisxTavbTuYVSsNJHetwq5bJvC' + 'QkjjtiLM2dCratiA' + timestamp
    _ = _.encode('utf-8')
    wif_signature = hashlib.sha256(_).hexdigest().upper()

    # Send post requests
    url = 'http://bmfw.www.gov.cn/bjww/interface/interfaceJson'
    data = {
        "appId": "NcApplication",
        "paasHeader": pass_header,
        "timestampHeader": timestamp,
        "nonceHeader": nonce,
        "signatureHeader": signatureHeader,
        "key": key
    }
    header = {
        "x-wif-nonce": "QkjjtiLM2dCratiA",
        "x-wif-paasid": "smt-application",
        "x-wif-signature": wif_signature,
        "x-wif-timestamp": timestamp,
        "Origin": "http://bmfw.www.gov.cn",
        "Referer": "http://bmfw.www.gov.cn/yqfxdjcx/risk.html",
        "Content-Type": "application/json; charset=UTF-8"
    }
    r = requests.post(url, data=json.dumps(data), headers=header)
    risk_json = r.json()

    highlist_str = []
    highlist = risk_json['data']['highlist']
    for i_high in range(0, len(highlist)):
        if highlist[i_high]['city'] == city + "市":
            for j_high in range(0, len(highlist[i_high]['communitys'])):
                highlist_str.append(highlist[i_high]['county'] + ' ' + highlist[i_high]['communitys'][j_high])
    middlelist_str = []
    middlelist = risk_json['data']['middlelist']
    for i_mid in range(0, len(middlelist)):
        if middlelist[i_mid]['city'] == city + "市":
            for j_mid in range(0, len(middlelist[i_mid]['communitys'])):
                middlelist_str.append(middlelist[i_mid]['county'] + ' ' + middlelist[i_mid]['communitys'][j_mid])
    lowlist_str = []
    lowlist = risk_json['data']['lowlist']
    for i_low in range(0, len(lowlist)):
        if lowlist[i_low]['city'] == city + "市":
            for j_low in range(0, len(lowlist[i_low]['communitys'])):
                lowlist_str.append(lowlist[i_low]['county'] + ' ' + lowlist[i_low]['communitys'][j_low])

    return '\n'.join(highlist_str), '\n'.join(middlelist_str), '\n'.join(lowlist_str), len(lowlist_str)



# 获取纪念日天数
def get_count():
    delta = today_solar - datetime.strptime(start_date, "%Y-%m-%d")
    return delta.days


# 获取倒计时天数
def get_exam_count():
    countdown = datetime.strptime(exam_date, "%Y-%m-%d") - today_solar
    return countdown.days


# 获取生日倒计时天数
def get_birthday(index, birth):
    if 'h' in index:
        if len(birth) == 10:
            birth = birth[5:10]
        next = datetime.strptime(str(date.today().year) + "-" + birth, "%Y-%m-%d")
        if next < today_solar:
            next = next.replace(year=next.year + 1)
        return (next - today_solar).days
        # 为读取农历生日准备
    elif 'g' in index:
        if len(birth) == 10:
            x = int(birth[0:4:1])  # 读取无用，为理解下面两行留着，可删去
            y = int(birth[5:7])  # 切片
            z = int(birth[8:10])
        elif len(birth) == 5:
            y = int(birth[0:2])  # 切片
            z = int(birth[3:5])
        next = LunarDate(today_lunar.year, y, z)
        if next < today_lunar:
            next = next.replace(year=next.year + 1)
        return (next - today_lunar).days


# 获取每日一言
def get_words():
    words = requests.get("https://api.shadiao.pro/chp")
    if words.status_code != 200:
        return get_words()
    return words.json()['data']['text']


# 随机颜色
def get_random_color():
    return "#%06x" % random.randint(0, 0xFFFFFF)


# 自定义菜单
client = WeChatClient(app_id, app_secret)
client.menu.create({
    "button": [
        {
            "type": "view",
            "name": "个人博客",
            "url": "https://waluna.top"
        },
        {
            "type": "view",
            "name": "机器人luna",
            "url": "https://openai.weixin.qq.com/webapp/MUVBpsFPvT1XTXhvn2IbUIdHVF3Jea?robotName=luna"
        },
        {
            "name": "提醒详情",
            "sub_button": [
                {
                    "type": "view",
                    "name": "墨迹天气",
                    "url": "http://m.moji.com/"
                },
                {
                    "type": "view",
                    "name": "疫情数据",
                    "url": "https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_aladin_banner"
                },
                {
                    "type": "view",
                    "name": "风险区（卫健委）",
                    "url": "http://bmfw.www.gov.cn/yqfxdjcx/"
                },
                {
                    "type": "view",
                    "name": "风险区（第三方数据）",
                    "url": "https://waluna.top/fengxian/"
                }
            ]
        }
    ]
})


client = WeChatClient(app_id, app_secret)
wm = WeChatMessage(client)

# 获取天气数据
ci, wea, temperature, highest, lowest = get_weather(city)
ci1, wea1, temperature1, highest1, lowest1 = get_weather(city1)

# 获取疫情数据
# local_wzz_add, local_confirm_add = get_virus(province, city)
# print(local_confirm_add, local_wzz_add)

local_wzz_add, local_confirm_add, dangerousAreas_high, dangerousAreas_mid, dangerousAreas_low = get_virus(province, city)
local_wzz_add1, local_confirm_add1, dangerousAreas_high1, dangerousAreas_mid1, dangerousAreas_low1 = get_virus(province1, city1)
# print(local_wzz_add, local_confirm_add, dangerousAreas_low, dangerousAreas_mid, dangerousAreas_high)

highlist_str, middlelist_str, lowlist_str, dangerousAreas_low_str = get_dangerousAreas(province, city)
highlist_str1, middlelist_str1, lowlist_str1, dangerousAreas_low1_str = get_dangerousAreas(province1, city1)
# print(highlist_str, middlelist_str, lowlist_str)

# local_confirm_add, wzz_add = get_virus(province, city)
# local_confirm_add1, wzz_add1 = get_virus(province1, city1)

if dangerousAreas_low == "全域无风险地区，落实常态化防控措施":
    dangerousAreas_low_str = '0个\n' + str(dangerousAreas_low)
elif int(dangerousAreas_low_str) > 0:
    dangerousAreas_low = dangerousAreas_low_str
    dangerousAreas_low_str = str(dangerousAreas_low) + '个'
else:
    dangerousAreas_low_str = str(dangerousAreas_low)

if dangerousAreas_low1 == "全域无风险地区，落实常态化防控措施":
    dangerousAreas_low_str1 = '0个\n' + str(dangerousAreas_low1)
elif int(dangerousAreas_low1_str) > 0:
    dangerousAreas_low1 = dangerousAreas_low1_str
    dangerousAreas_low_str1 = str(dangerousAreas_low1) + '个'
else:
    dangerousAreas_low_str1 = str(dangerousAreas_low1)

lowColor = "#10AEB5"
midColor = "#FFA90E"
highColor = "#EB3333"

# 所有模板数据
data = {
    "1": {"value": today_solar_str, "color": get_random_color()},
    "2": {"value": today_lunar_str, "color": get_random_color()},
    "3": {"value": ci, "color": get_random_color()},
    "4": {"value": wea, "color": get_random_color()},
    "5": {"value": str(temperature) + "℃", "color": get_random_color()},
    "6": {"value": str(lowest) + "℃ ~ " + str(highest) + "℃", "color": get_random_color()},
    "7": {"value": local_confirm_add, "color": get_random_color()},
    "8": {"value": local_wzz_add, "color": get_random_color()},
    "9": {"value": ci1, "color": get_random_color()},
    "a": {"value": wea1, "color": get_random_color()},
    "b": {"value": str(temperature1) + "℃", "color": get_random_color()},
    "c": {"value": str(lowest1) + "℃ ~ " + str(highest1) + "℃", "color": get_random_color()},
    "d": {"value": local_confirm_add1, "color": get_random_color()},
    "e": {"value": local_wzz_add1, "color": get_random_color()},
    "f": {"value": get_exam_count(), "color": get_random_color()},
    "i": {"value": get_count(), "color": get_random_color()},
    "j": {"value": '彩虹屁：' + get_words(), "color": get_random_color()},
    "k": {"value": "高风险地区" + str(dangerousAreas_high) + '个', "color": highColor},
    "l": {"value": "中风险地区" + str(dangerousAreas_mid) + '个', "color": midColor},
    "m": {"value": "低风险地区" + dangerousAreas_low_str, "color": lowColor},
    "n": {"value": "高风险地区" + str(dangerousAreas_high1) + '个', "color": highColor},
    "o": {"value": "中风险地区" + str(dangerousAreas_mid1) + '个', "color": midColor},
    "p": {"value": "低风险地区" + dangerousAreas_low_str1, "color": lowColor},
}

# 获取农历生日倒计时
for index, i in enumerate(birthday_lunar):
    g = "g%d" % index
    data[g] = {
        "value": get_birthday(g, i),
        "color": get_random_color()
    }

# 获取阳历生日倒计时
for index, i in enumerate(birthday_solar):
    h = "h%d" % index
    data[h] = {
        "value": get_birthday(h, i),
        "color": get_random_color()
    }

# print(data)

count = 0
for user_id in user_ids:
    res = wm.send_template(user_id, template_id, data, url)
    count += 1

print("发送了" + str(count) + "条消息")
